<?php

namespace api\lib;

trait ErrorLog
{
    private $logPath = "";

    private $prefix = "";

    /** @var resource */
    private static $logHandler;

    protected function init() {
        $dir = PROJECT_DIR . '/data/log';
        if (!file_exists($dir)) {
            mkdir($dir, 0755, true);
        }
        if (empty($logPath)) {
            $this->logPath = $dir.'/record_'.date("Y-m-d",time()).'.log';
        }
        if (empty($this->prefix)) {
            $this->prefix = "[" . date("Y-m-d H:i:s", time()) . "] ";
        }
    }

    public function writeLog(/* string */$content) {
        $this->init();
        if (empty(self::$logHandler) || !is_resource(self::$logHandler)) {
            self::$logHandler = fopen($this->logPath, 'w');
            if (!is_resource(self::$logHandler)) {
                throw new \ErrorException("打开日志文件".$this->logPath."失败");
            }
        }
        fwrite(self::$logHandler, $this->prefix.$content.PHP_EOL);
    }

    public function __destruct() {
        if (is_resource(self::$logHandler) && !empty(self::$logHandler)) {
            fclose(self::$logHandler);
            self::$logHandler = null;
        }
    }
}